﻿#pragma strict

var massY:float = -2;
var steerAngle:float = 15;
var brakeTorque:float = 40;
var maxTorque:float = 50;

var lt:WheelCollider;
var rt:WheelCollider;
var lb:WheelCollider;
var rb:WheelCollider;

var ltMesh:Transform;
var rtMesh:Transform;
var lbMesh:Transform;
var rbMesh:Transform;

var speed:float;

private var ltRot:float;
private var rtRot:float;
private var lbRot:float;
private var rbRot:float;

function Start () {
	rigidbody.centerOfMass.y = massY;
}

function FixedUpdate () {
	var h:float = Input.GetAxis("Horizontal");
	var v:float = Input.GetAxis("Vertical");
	
	var isBrake:boolean = Input.GetKey(KeyCode.Space);
	
	lt.steerAngle = h * steerAngle;
	rt.steerAngle = h * steerAngle;
	
	lb.motorTorque = maxTorque * v;
	rb.motorTorque = maxTorque * v;
	
	SyncWheelRotation();
	
	BrakeBack(isBrake);
	
	CalcSpeed(rb);
}
//-轮子 旋转
function SyncWheelRotation(){
	ltRot += GetRollAngle(lt);
	lbRot += GetRollAngle(lb);
	rtRot += GetRollAngle(rt);
	rbRot += GetRollAngle(rb);
	
	ltMesh.localRotation = Quaternion.Euler(ltRot,lt.steerAngle,90);
	rtMesh.localRotation = Quaternion.Euler(rtRot,rt.steerAngle,90);
	lbMesh.localRotation = Quaternion.Euler(lbRot,0,90);
	rbMesh.localRotation = Quaternion.Euler(rbRot,0,90);
}

function GetRollAngle(wheel:WheelCollider){
	return wheel.rpm / 60 * 360 * Time.deltaTime; //rpm,转/分. /60,转/秒,*360,旋转角度/帧,*Time.deltaTime:旋转角的/秒
}

//后轮 制动.
function BrakeBack(isBrake:boolean){
	var torque:float = 0;
	if(isBrake){
		torque = brakeTorque;
	}
	lb.brakeTorque = torque;
	rb.brakeTorque = torque;
}

function CalcSpeed(wheel:WheelCollider){
	speed = 2 * 3.14159 * wheel.rpm * wheel.radius * 60 / 1000;
}